package com.example.community.controller;

import com.example.community.dao.pojo.DiscussPost;
import com.example.community.dao.pojo.Page;
import com.example.community.service.ElasticsearchService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;
import com.example.community.uitls.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SearchController
 * @Description:
 * @Author
 * @Date 2022-03-27
 * @Version 1.0
 */
@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) throws IOException {


        page.setLimit(2);
        page.setPath("/search?keyword=" + keyword);

        //聚合数据
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        List<DiscussPost> Posts = elasticsearchService.
                searchDiscussPost(keyword, page.getCurrent(), page.getLimit());

        if (Posts!=null){
            for (DiscussPost post : Posts){
                Map<String,Object> map = new HashMap<>();
                //帖子
                map.put("post",post);
                //作者
                map.put("user",userService.findUserById(post.getUserId()));
                //点赞数量
                map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussPosts.add(map);

            }
        }


        assert Posts != null;
        page.setRows((int) elasticsearchService.searchDiscussPostCount(keyword));

        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("keyword",keyword);

        return "/site/search";
    }
}
